﻿using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Runtime.Remoting.Messaging;

namespace Api.Common
{
    /// <summary>
    /// deciaml 固定小数点
    /// 123-> 123.00
    /// 123.0-> 123.00
    /// 123.119->123.12
    /// </summary>
    public class DecimalConverter : JsonConverter
    {
        public override bool CanConvert(Type objectType)
        {
            return objectType == typeof(decimal) ||
                objectType == typeof(decimal?) ||
                objectType == typeof(double) ||
                objectType == typeof(double?) ||
                objectType == typeof(float) ||
                objectType == typeof(float?);
        }

        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {
            throw new NotImplementedException();
        }

        public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
        {
            JToken.FromObject(Convert(value)).WriteTo(writer);
        }

        /// <summary>
        /// 这里只负责截取所有decimal，double等参数的小数位，而不管千分位
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        private string Convert(object obj)
        {
            if (obj == null)
            {
                return "null";
            }
            var length = (int)(CallContext.GetData("decimals") ?? 2);
            var fstr = "";
            if (length > 0)
            {
                fstr = string.Concat("f", length); //使用fn表示截取n位小数
            }
            var a = obj as Decimal?;

            if (a != null)
            {
                var value = System.Convert.ToDecimal(a.Value.ToString());
                return Math.Round(value, length).ToString(fstr);
            }
            else
            {
                var b = obj as double?;
                if (b != null)
                {
                    var value = System.Convert.ToDouble(b.Value.ToString());
                    return Math.Round(value, length).ToString(fstr);
                }
                else
                {
                    var c = obj as float?;
                    if (c != null)
                    {
                        var value = System.Convert.ToDouble(c.Value.ToString());
                        return Math.Round(value, length).ToString(fstr);
                    }
                }
            }
            return string.Empty;
        }
    }
}